package org.example.server;

import com.alibaba.fastjson.JSONObject;
import org.example.server.read.ReadStrategy;

import java.net.Socket;
import java.util.HashMap;

public class JSONRead {
    private ReadStrategy readStrategy = null;
    private JSONObject jsonObject;
    private Socket socket ;
    private HashMap<String, String> map = new HashMap<String, String>() {
        {
            put("send", "ServerSendStrategy");
            put("user", "UserReadStrategy");
            put("register", "RegisterStrategy");
        }
    };

    public JSONRead(StringBuffer stringBuffer, Socket socket) {
        this.socket = socket;
        try {
            jsonObject = JSONObject.parseObject(stringBuffer.toString());

            // 根据头部数据type的键来判断使用哪种策略
            Class c = Class.forName("org.example.server.read." + map.get(jsonObject.getString("type")));
            readStrategy = (ReadStrategy) c.newInstance();
            readStrategy.setDataJsonObject(jsonObject);
            readStrategy.setSocket(socket);
        } catch (Exception e) {
            System.out.println("com.tmf.server.JSONRead:JSONRead(): 传输非JSON数据");
            e.printStackTrace();
        }
    }

    public int operateData() {
        try {
            readStrategy.operateData();
            if (jsonObject.containsKey("type")) {
                return 1;
            } else {
                return 0;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static String getUserID(StringBuffer request) {
        JSONObject jsonObject = JSONObject.parseObject(request.toString());
        return jsonObject.getString("userID");
    }
}
